package com.fr.lintcode;

import java.util.List;
import java.util.Stack;

public class Q1116 {
    /**
     * @param n:
     *            a integer
     * @param logs:
     *            a list of integers
     * @return: return a list of integers
     */
    public int[] exclusiveTime(int n, List<String> logs) {
        // write your code here
        if (n <= 0 || logs == null | logs.size() <= 0) {
            return null;
        }
        int[] costs = new int[n];
        int lastId = -1;
        int lastTime = 0;
        String lastStatus = null;
        Stack<Integer> stack = new Stack<>();
        for (String log : logs) {
            String[] s = log.split(":");
            int id = Integer.parseInt(s[0]);
            int time = Integer.parseInt(s[2]);

            if ("start".equals(s[1])) {
                if (lastId >= 0) {
                    int cost = 0;
                    if ("start".equals(lastStatus)) {
                        cost = time - lastTime;
                        costs[lastId] = costs[lastId] + cost;
                    } else if ("end".equals(lastStatus)) {
                        if (!stack.isEmpty()) {
                            cost = time - lastTime - 1;
                            int i = stack.peek();
                            costs[i] = costs[i] + cost;
                        }

                    }

                }
                stack.push(id);

            } else if ("end".equals(s[1])) {
                int cost = 0;
                if ("start".equals(lastStatus)) {
                    cost = time - lastTime + 1;
                } else if ("end".equals(lastStatus)) {
                    cost = time - lastTime;
                }
                stack.pop();
                costs[id] = costs[id] + cost;
            }
            lastId = id;
            lastTime = time;
            lastStatus = s[1];
        }
        return costs;

    }

}
